package com.zy.mc_module.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewTreeObserver;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.zy.mc_module.R;
import com.zy.mc_module.base.App;
import com.zy.mc_module.utils.AppTools;
import com.zy.mc_module.utils.NetUtil;
import com.zy.mc_module.utils.SystemUtil;

/**
 * Created on 18/11/3
 * scrollview嵌套webview
 * webview的缓存
 */
public class MyWebView extends WebView {
    private static String TAG = "MyWebView";
    private boolean isFinished = false;
    private Activity activity;
    private ViewTreeObserver.OnGlobalLayoutListener OnGlobalLayoutListener;

    private webFinishedListener webFinishedListener;
    private CustomHeadLayout customHead;

    public MyWebView() {
        super(App.getAppContext());
        init(App.getAppContext());
    }

    public MyWebView(Activity activity) {
        super(activity);
        this.activity = activity;
        init(App.getAppContext());
    }

    public MyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    //    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    //        int mExpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
    //        super.onMeasure(widthMeasureSpec, mExpandSpec);
    //    }

    /***
     * 初始化
     */
    private void init(Context context) {
        setOverScrollMode(View.OVER_SCROLL_NEVER);
        //取消Vertical ScrollBar显示
        setVerticalScrollBarEnabled(false);
        setVerticalScrollbarOverlay(false);
        //取消Horizontal ScrollBar显示
        setHorizontalScrollBarEnabled(false);
        setHorizontalScrollbarOverlay(false);
        getSettings().setJavaScriptEnabled(true);
        //设置自适应屏幕，两者合用
        getSettings().setUseWideViewPort(false); //将图片调整到适合webview的大小
        getSettings().setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//支持内容重新布局
        //设置可以访问文件
        getSettings().setAllowFileAccess(true);
        // 支持缩放
        getSettings().setSupportZoom(false);
        //控制字体大小不随系统设置变化
        getSettings().setTextZoom(100);
        //提高渲染的优先级
        getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        //开启DomStorage缓存
        getSettings().setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.0之后https加载非安全站点(http)时不被允许
            getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //设置WebView的缓存
        if (NetUtil.isNetwork()) {
            getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        } else {
            getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        }
        //开启缓存
        setWebCache(context, true);

        //辅助 WebView 处理 Javascript 的对话框,网站图标,网站标题等等
        setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress > 90 && null != webFinishedListener) {
                    webFinishedListener.webFinished();
                    isFinished = true;
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (null != customHead) {
                    if (TextUtils.isEmpty(title)) {
                        customHead.setText("加载中...");
                    } else {
                        customHead.setText(title);
                    }
                }
            }

            // 本人以为5.0以前的大可不必处理，现在新建的android项目minSDK都建议22（也就是android5.0）起步了，再说了目前的环境先5.0以前的系统还真不好找，除了老年机
            // For Android 5.0+
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                if (fileChooser != null)
                    return fileChooser.onShowFileChooser(webView, filePathCallback, fileChooserParams);
                return true;
            }
        });
        //网页打开时,不调用系统浏览器
        setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //TODO: 18/12/19 暂时去掉外链点击事件
                //view.loadUrl(url);
                //return true;
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return false;
                } else {
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        context.startActivity(intent);
                        return true;
                    } catch (Exception e) {
                        return false;
                    }
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                getSettings().setBlockNetworkImage(false);
                //判断webview是否加载了，图片资源
                if (!getSettings().getLoadsImagesAutomatically()) {
                    //设置wenView加载图片资源
                    getSettings().setLoadsImagesAutomatically(true);
                }
                if (!isFinished && null != webFinishedListener) {
                    webFinishedListener.webFinished();
                    isFinished = true;
                }
                super.onPageFinished(view, url);
                addImageClickListener(view);//待网页加载完全后设置图片点击的监听方法
            }
        });
        //屏蔽长按事件
        //setOnLongClickListener(v -> true);

        //获取正确高度,重新设置
        this.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver
                .OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                if (getHeight() != 0 && getMeasuredHeight() != 0 && getContentHeight() != 0) {
                    OnGlobalLayoutListener = this;
                    float density = AppTools.getDensity(getResources().getDisplayMetrics().density);
                    if (SystemUtil.isMeasure()) {
                        getLayoutParams().height = Math.max(getHeight(), ((int) (density * getContentHeight())));
                        setLayoutParams(getLayoutParams());
                    }
                    new Handler().postDelayed(() -> {
                        if (null != OnGlobalLayoutListener) {
                            getViewTreeObserver().removeGlobalOnLayoutListener(OnGlobalLayoutListener);
                        }
                    }, 1500);
                }
            }
        });
    }

    private void addImageClickListener(WebView webView) {
        webView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName(\"img\"); " +
                "for(var i=0;i<objs.length;i++)  " +
                "{"
                + "    objs[i].onclick=function()  " +
                "    {  "
                + "        window.imagelistener.openImage(this.src);  " +//通过js代码找到标签为img的代码块，设置点击的监听方法与本地的openImage方法进行连接
                "    }  " +
                "}" +
                "})()");
    }

    /***
     * 设置WebView背景色
     */
    public void setBackground(int color) {
        this.setBackgroundResource(R.color.transparent);
        this.setBackgroundColor(color); //设置背景色
        this.getBackground().setAlpha(0);
    }

    /***
     * 重写加载富文本,适配图片
     * @param data
     */
    public void loadDataWithBaseURL(String data) {
        if (null == data) {
            return;
        }
        String content = data.replace("<img", "<img style=\"max-width:100%;height:auto\"");
        super.loadDataWithBaseURL(null, content, "text/html", "utf-8", null);
        //super.loadDataWithBaseURL(baseUrl, content, mimeType, encoding, historyUrl);
    }

    public void setTitle(CustomHeadLayout customHead) {
        this.customHead = customHead;
    }

    /***
     * WebView时候缓存
     * 默认开启
     */
    public void setWebCache(Context context, boolean isCache) {
        if (isCache) {
            String cacheDirPath = context.getFilesDir().getAbsolutePath() + "/webCache";
            getSettings().setAppCachePath(cacheDirPath); //设置缓存目录
            getSettings().setAppCacheEnabled(true);//开启Application 缓存机制
            getSettings().setDomStorageEnabled(true);
        }
    }

    public void setonWebFinished(webFinishedListener webFinished) {
        this.webFinishedListener = webFinished;
    }

    public interface webFinishedListener {
        void webFinished();
    }

    public void onDestroy() {
        try {
            if (null != this) {
                if (null != OnGlobalLayoutListener) {
                    getViewTreeObserver().removeGlobalOnLayoutListener(OnGlobalLayoutListener);
                }
                ViewParent parent = this.getParent();
                if (parent != null) {
                    ((ViewGroup) parent).removeView(this);
                }
                clearHistory();
                removeAllViews();
                destroy();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    ShowFileChooser fileChooser;

    public void setFileChooser(ShowFileChooser fileChooser) {
        this.fileChooser = fileChooser;
    }

    public interface ShowFileChooser {
        boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams);
    }
}
